import dayjs from "dayjs";
import { getProxyRequest } from "../http/api/proxy";
import { HttpsProxyAgent } from "https-proxy-agent";

export let allowProxy = false;
export let ipProxy: any;

export const getProxy = async () => {
    try {
        const res = await getProxyRequest();
        const { code, data } = res.data;

        if (code === "SUCCESS") {
            return data?.[0];
        } else {
            return Promise.reject(new Error("获取代理失败"));
        }
    } catch (e) {
        return Promise.reject(e);
    }
};

const executeProxyTimeout = async () => {
    if (allowProxy) {
        return await getProxy()
            .then((proxy: any) => {
                console.log(`切换IP时间:${dayjs().format("YYYY-MM-DD HH:mm:ss")}`);
                ipProxy = proxy;
                console.log(`deadline:${proxy?.deadline}`);
                const diff =
                    (dayjs(proxy?.deadline).diff(dayjs(), "milliseconds") || 0) - 3000;
                if (diff > 0) {
                    setTimeout(() => {
                        executeProxyTimeout();
                    }, diff);
                }
            })
            .catch((e) => {
                console.log("获取代理失败,10秒后重试");
                setTimeout(() => {
                    executeProxyTimeout();
                }, 10000);
            });
    } else {
        ipProxy = undefined;
    }
};
export const startProxy =async () => {
    console.log("开始代理");
    allowProxy = true;
    await executeProxyTimeout();
}

export const closeProxy = () => {
    console.log("关闭代理");
    allowProxy = false;
}

export const getProxyAgent = () => {
  if (!ipProxy?.server) {
    return undefined;
  }
  const authKey = "IU9G01YW";
  const authPwd = "53C02764EF0E";
  const proxyUrl = `http://${authKey}:${authPwd}@${ipProxy.server}`;
  return new HttpsProxyAgent(proxyUrl);
};